package br.net.woodstock.tickettoride.web.jsf.security.common;

import br.net.woodstock.tickettoride.api.access.UserService;
import br.net.woodstock.tickettoride.api.core.TicketLog;
import br.net.woodstock.tickettoride.orm.User;
import br.net.woodstock.tickettoride.web.jsf.TTRBean;

public abstract class AbstractLoginBean extends TTRBean {

	private static final long	serialVersionUID	= 365982448995745841L;

	private String				login;

	private String				password;

	public AbstractLoginBean() {
		super();
	}

	public abstract UserService getUserService();

	public String start() {
		return JSFConstants.LOGIN_PAGE;
	}

	public String login() {
		User user = this.getUserService().getByLoginPassword(this.login, this.password);
		if (user != null) {
			JSFSecurityUtils.setSessionUser(user);
			this.onLogin(user);
			return JSFConstants.INDEX_PAGE;
		}
		return null;
	}

	public String logout() {
		User user = JSFSecurityUtils.getSessionUser();
		this.onLogout(user);
		JSFSecurityUtils.setSessionUser(null);
		return JSFConstants.INDEX_PAGE;
	}

	public void onLogin(final User user) {
		TicketLog.getLog().info("User " + user.getLogin() + " logged in");
	}

	public void onLogout(final User user) {
		TicketLog.getLog().info("User " + user.getLogin() + " logged out");
	}

	public String cancel() {
		return JSFConstants.INDEX_PAGE;
	}

	// Getters and Setters
	public String getLogin() {
		return this.login;
	}

	public void setLogin(final String login) {
		this.login = login;
	}

	public String getPassword() {
		return this.password;
	}

	public void setPassword(final String password) {
		this.password = password;
	}

}
